/**
 * 地块绘制工具
 */
import Base from "./Base";
import MapCommon from "../common/MapCommon";
import _ from "lodash"



export default class SelectPolygon extends Base {
  constructor(map,{callBack:callBack,errorCallBack:errorCallBack,clickLayers:clickLayers,features=[],clickLayersFilters=[]}) {
    super(map,'SelectPolygon',{callBack:callBack,errorCallBack:errorCallBack});
    this.clickLayers=[];//点击查询的图层
    for (let i = 0; i <clickLayers.length ; i++) {
      MapCommon.copyLineToAreaFit(this.map,clickLayers[i],clickLayers[i]+"_select");
      this.clickLayers.push(clickLayers[i]+"_select");
    }
    //初始化已选择要素
    this.selectSet={
      "type": "FeatureCollection",
      "features": features||[]

    };//已选择要素集
    this.mode = 'multi';//多选模式
    this.tempLayerName="selectionSetDraw";
    this.clickLayersFilters=clickLayersFilters;
  }

  start() {
    super.start();
    //将所有点击线图层转化为面图层
    //增加高亮图层
    if (!this.map.getSource(this.tempLayerName)) {
      this.map.addSource(this.tempLayerName, {
        "type": "geojson",
        "data": this.selectSet
      });
    }
    //添加选择集图层
    if (!this.map.getLayer(this.tempLayerName)) {
      this.map.addLayer({
        id: this.tempLayerName,
        source: this.tempLayerName,
        "minzoom": 7,
        "maxzoom": 18,
        type: 'line',
        "paint": {
          "line-color": "#f00",
          "line-opacity": 1,
          "line-width": 6
        },
      });
    }
   this.clickEvent=(e)=>{
     this.select([e.originalEvent.layerX, e.originalEvent.layerY])
   }

    //添加点击事件
    this.map.on('click', this.clickEvent);
  }

  /**
   * 通过点查询用户点击的面要素
   * @param point
   */
  select(point){
    if(this.clickLayers.length===0){
      return;
    }
    let renderFeatures = this.map.queryRenderedFeatures(point, {layers: this.clickLayers});
  if(!renderFeatures||renderFeatures.length===0){
    return;
  }

    //确定优先选中的要素
    let priorityRenderF = this.getPriorityRenderFeature(renderFeatures);

    //避免地块被切片分割的问题
    let features = this.map.querySourceFeatures(priorityRenderF.layer.source, {'sourceLayer': priorityRenderF.layer.source, 'filter': ['==', 'objectid', priorityRenderF.properties.objectid]});
    let temp = MapCommon.unionFeatures(features);
    temp.properties=priorityRenderF.properties;
    temp.source=priorityRenderF.source;
    temp.sourceLayer=priorityRenderF.sourceLayer;
    temp.layer=priorityRenderF.layer;

    priorityRenderF=temp;
    priorityRenderF.properties.myobjectid=priorityRenderF.source+priorityRenderF.properties.objectid;
    // 判断正选反选
    let anti_index = this.isAnti_Election(priorityRenderF);


    this.update(priorityRenderF, anti_index);

  }

  //更新source
  update(feature, anti_index) {
    //反选
    if (anti_index > -1) {
      //选中后,再取消走这
      this.selectSet.features = _.filter(this.selectSet.features, (o) => {
        return o.properties.myobjectid !== feature.properties.myobjectid
      })
    }
    //非反选
    if (anti_index < 0) {
      // 头一次选中-->走这
      this.mode === 'multi' ? this.selectSet.features.push(feature) : this.selectSet.features = [feature]
    }
    if (this.map.getSource('selectionSetDraw')) {
      //  不管第几次选,都会走这
      this.map.getSource('selectionSetDraw').setData(this.selectSet);
    }
    //将每次数据回调
   this.finish(this.selectSet)

  }

  //-1非反选; >-1反选
  isAnti_Election(sourceF) {
    if (!sourceF) {
      return
    }
    let myobjectid = sourceF.properties['myobjectid'];
    let index = _.findIndex(this.selectSet.features, (feature) => {
      return feature.properties.myobjectid === myobjectid
    })
    return index
  }


  //获取优先级高的图层要素
  getPriorityRenderFeature(features) {
    let priority = null;
    for (let i = 0; i < this.clickLayers.length; i++) {
      let index = _.findIndex(features, (renderF) => {
        if(renderF.layer.id === this.clickLayers[i]){
          let filters=this.clickLayersFilters.filter(item=>
            (item.layer+"_select")===renderF.layer.id
          );
          if(filters.length===0){
            return true;
          }

          let filter=filters[0];

          if(renderF.properties&&renderF.properties[filter.key]&&renderF.properties[filter.key]==filter.value){
             return false
          }else {
            return true;
          }
        }else {
          return false;
        }
      });

      if (index > -1) {
        priority = JSON.parse(JSON.stringify(features[index]));
        break
      }
    }
    return priority
  }



  close(notClearMap=false) {
    this.clear(notClearMap);
    this.clearEvent();
  }

  clear(notClearMap=false) {
    this.clearMap(notClearMap);
  }

  clearMap(notClearMap=false) {
    //不清除地图选择绘制图层
    if(!notClearMap){
     super.clearMap();
    }

    for (let i = 0; i <this.clickLayers.length ; i++) {
      if (this.map.getLayer(this.clickLayers[i])) {
        this.map.removeLayer(this.clickLayers[i]);
      }
    }

  }

  clearEvent() {
    super.clearEvent();
    this.map.off('click',this.clickEvent);
    this.selectSet={
      "type": "FeatureCollection",
      "features": [
      ]
    };
    this.clickLayers=[];
  }
}
